package com.linln.admin.welfare.controller;

import com.linln.admin.welfare.domain.Welfare;
import com.linln.admin.welfare.service.WelfareService;
import com.linln.common.enums.StatusEnum;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.StatusUtil;
import com.linln.common.vo.ResultVo;
import com.linln.component.shiro.ShiroUtil;
import com.linln.modules.system.domain.Dept;
import com.linln.modules.system.service.DeptService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wcy
 * @date 2020/03/14
 */
@Controller
@RequestMapping("/welfare/audit")
public class AuditController {

    @Autowired
    private WelfareService welfareService;
    @Autowired
    private DeptService deptService;

    /**
     * 列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("welfare:audit:index")
    public String index(Model model, Welfare welfare) {

        //显示当前用户所在的部门，部门下面所有的用户的申请表
        List<Long> deptlist = deptService.getListByPidLikeOk(ShiroUtil.getSubject().getDept().getId()).stream()
                .map(Dept::getId).collect(Collectors.toList());

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("code", match -> match.contains());

        // 获取数据列表
        Example<Welfare> example = Example.of(welfare, matcher);
        Page<Welfare> list = welfareService.getPageList(example);

        list.getContent().forEach(line->{
            if (!StringUtils.isEmpty(line.getStartDate())){
                line.setStartDate(line.getStartDate().replace("T"," "));
                line.setEndDate(line.getEndDate().replace("T"," "));
            }
        });
        //将所有的表进行匹配，匹配本部门下面所有部门ID
        // 封装数据
//        model.addAttribute("list", list.getContent().stream()
//                .filter(line->deptlist.contains(line.getCreateBy().getDept().getId()))
//                .collect(Collectors.toList()));
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        return "/welfare/audit/index";
    }

    @GetMapping("/cancel")
    @RequiresPermissions("welfare:audit:cancel")
    public String cancel(Model model, Welfare welfare) {

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("code", match -> match.contains());

        if (welfare.getStatus().intValue() != 5 && welfare.getStatus().intValue()!= 4){
            welfare.setStatus((byte) 4);
        }
        // 获取数据列表
        Example<Welfare> example = Example.of(welfare, matcher);
        Page<Welfare> list = welfareService.getPageList(example);

        //将所有的表进行匹配，匹配本部门下面所有部门ID
        // 封装数据
        list.getContent().forEach(line->{
            if (!StringUtils.isEmpty(line.getStartDate())){
                line.setStartDate(line.getStartDate().replace("T"," "));
                line.setEndDate(line.getEndDate().replace("T"," "));
            }
        });
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        return "/welfare/audit/cancel";
    }

    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail/{id}")
//    @RequiresPermissions("welfare:audit:detail")
    public String toDetail(@PathVariable("id") Welfare welfare, Model model) {
        model.addAttribute("welfare",welfare);
        return "/welfare/welfare/detail";
    }

    /**
     * 设置一条或者多条数据的状态
     */
    @RequestMapping("/status/{param}")
//    @RequiresPermissions("welfare:audit:status")
    @ResponseBody
    public ResultVo status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<Long> ids) {
        // 更新状态
        StatusEnum statusEnum = StatusUtil.getStatusEnum(param);
        if ("cancel".equals(param)){
            for (Long id :ids) {
                Welfare beWelfare = welfareService.getById(id);
                beWelfare.setStatus((byte) 5);
                welfareService.save(beWelfare);
            }
            return ResultVoUtil.success(statusEnum.getMessage() + "成功");
        }
        if (welfareService.updateStatus(statusEnum, ids)) {
            int code = statusEnum.getCode();
            if (code==2){
                for (Long id :ids) {
                    Welfare welfare = welfareService.getById(id);
                    welfare.setStatus((byte) 1);
                    welfare.setMove(1L);
//                    welfare.setMove(ShiroUtil.getSubject().getDept().getPid());
                    welfareService.save(welfare);
                }
            } else{
                //将所有的驳回
                for (Long id :ids) {
                    Welfare welfare = welfareService.getById(id);
                    welfare.setStatus((byte) 0);
                    welfareService.save(welfare);
                }
            }
            return ResultVoUtil.success(statusEnum.getMessage() + "成功");
            //更换所有的流转ID
        } else {
            return ResultVoUtil.error(statusEnum.getMessage() + "失败，请重新操作");
        }
    }
}